package com.dzm.xgb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.dzm.xgb.oss.properties.OssProperties;
import com.dzm.xgb.oss.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 作者：Dzm
 * 时间：2024-09-04-10:34
 * 功能：
 */

@Service
public class FileServiceImpl implements FileService {


    @Override
    public String upload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
//        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String endpoint = OssProperties.ENDPOINT;
        //获取当前日期
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        //获取UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String module = "default";

        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = module + "/" + format + "/" + uuid + suffix;

        // 填写Bucket名称，例如examplebucket。
        String bucketName = OssProperties.BUCKET_NAME;
        //获取key和secret
        String accessKey = OssProperties.ACCESS_KEY;
        String accessSecret = OssProperties.ACCESS_SECRET;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessSecret);

        try {
            InputStream is = file.getInputStream();
            ossClient.putObject(bucketName, objectName, is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }

    @Override
    public void remove(String fileUrl) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = OssProperties.ENDPOINT;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = OssProperties.BUCKET_NAME;
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = fileUrl.replace("https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/", "");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, OssProperties.ACCESS_KEY, OssProperties.ACCESS_SECRET);
        try {
            // 删除文件。
            ossClient.deleteObject(bucketName, objectName);
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
